package com.ase.数据结构.判断是否有环;

/**
 * @author gyhstart
 * @create 2021/2/28 - 21:40
 **/
public class tryIsCycle {

    private static int tryIsCycle(Node node) {
        //环的长度
        int loopLength = 0;
        Node node1 = node;
        Node node2 = node;

        while (node2 != null && node2.next != null) {
            node1 = node1.next;
            node2 = node2.next.next;
            if (node1 == node2) {
                System.out.println("node2 = " + node2.data);
                while (node2 != null && node2.next != null){
                    System.out.println("重新开始");
                    Node px = node2.next;
                    Node py = node2.next.next;
                    System.out.println("px = " + px.data);
                    System.out.println("py = " + py.data);
                    loopLength++;
                    if (px == py){
                        return loopLength;
                    }
                }
                return loopLength;
            }
        }

        return 0;
    }


    private static class Node {
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
        }
    }

    public static void main(String[] args) {

        Node node1 = new Node(5);
        Node node2 = new Node(3);
        Node node3 = new Node(7);
        Node node4 = new Node(2);
        Node node5 = new Node(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node2;

        System.out.println("getLoopSize(node1,node1) = " + tryIsCycle(node1));
    }
}
